#include "Bullet.h"
#include "Enemy.h"
#include "Weapon.h"
#include "ShootEmUp.h"
#include "GameManager.h"
#include "MainCharacter.h"

using namespace Ogre;

int Bullet::ID=0;
const char* Bullet::DEFAULT_NAME="bullet_";
const char* Bullet::DEFAULT_NODE_NAME="BulletNode";

Bullet::Bullet(Weapon* _weapon, Entity* entity, const Vector3& position)
: Item(Bullet::DEFAULT_NAME + StringConverter::toString(Bullet::ID)),
weapon(_weapon)
{
	Bullet::ID++;
	mEntity = entity;
	mSceneMgr = ShootEmUp::getSingleton().getSceneManager();
	initialize();
	mSceneNode->setPosition( position );
}

Bullet::~Bullet()
{
}

void Bullet::initialize()
{
	moveSpeed = ShootEmUp::getSingleton().getScrollingSpeed()*4;

	mEntity->setUserObject( this );
	mEntity->setVisible( true );
	
	mSceneNode = mSceneMgr->getSceneNode(Bullet::DEFAULT_NODE_NAME)->createChildSceneNode(Bullet::DEFAULT_NODE_NAME+std::string("_")+getName());
	mSceneNode->pitch((const Ogre::Radian)Angle(90));
	if ( mEntity->isAttached() )
		mEntity->getParentSceneNode()->detachObject( mEntity );
	mSceneNode->attachObject( mEntity );
}

bool Bullet::move()
{
	switch( weapon->getWeaponType() )
	{
	case Weapon::BUG:
		if ( mSceneNode->getPosition().z > (ShootEmUp::WORLD_MIN.z - 100) )
		{
			mSceneNode->translate(Vector3::NEGATIVE_UNIT_Z * moveSpeed);
			return true;
		}
		break;
	default:
		if ( mSceneNode->getPosition().z < ShootEmUp::WORLD_MAX.z + 150 )
		{
			mSceneNode->translate(Vector3::UNIT_Z * moveSpeed);
			return true;
		}
		break;
	}

	weapon->destroyBullet( this );
	return false;
}

void Bullet::collision(Item* _item)
{
	_item->collisionWithBullet( this );
}

void Bullet::collisionWithBullet(Bullet* _bullet)
{
	// do nothing !
}

void Bullet::collisionWithEnemy(Enemy* _enemy)
{
	_enemy->collisionWithBullet( this );
}

void Bullet::collisionWithFish(Fish * _fish)
{}

void Bullet::collisionWithMainCharacter(MainCharacter* _mainCharacter)
{
	if ( weapon->getWeaponType() == Weapon::BUG )
		_mainCharacter->collisionWithBullet( this );
}

void Bullet::collisionWithBonus(Bonus* _bonus)
{}

void Bullet::collisionWithWeapon(Weapon* weapon)
{}

bool Bullet::frameStarted(const FrameEvent& evt)
{
	move();
	return true;
}

void Bullet::reset(const Vector3& position)
{
	mSceneNode->setPosition( position );
	if ( mEntity->isAttached() )
		mEntity->getParentSceneNode()->detachObject( mEntity );
	mSceneNode->attachObject( mEntity );
}